﻿using DynamicListView.Controls;
using INTEX.DataBase;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using ReflectionStudio.Core.Helpers;
using System.Xml;
using System.Linq;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class YCAFSPLAN : DocumentBase
    {
        #region-------------Properties-----------------------
        DataRow LastRow = null;
        public OracleConnection OracleDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public DataSet dsResult;
        YCAFSPLANData m_Data, m_DataX;
        public DataSet dsParamaters;
        YCAFSPLANReport m_rpt;
        DataTable tbUser = null;
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB SetProd
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetProd");
            }
        }
        public SETINTEXDB SetEnv
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetEnv");
            }
        }

        bool IsAutoBackCalulate
        {
            get
            {
                if (ChkAutoBackCalulate.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    ChkAutoBackCalulate.IsChecked = true;
                }
                else
                {
                    ChkAutoBackCalulate.IsChecked = false;
                }
            }
        }
        string EKPBEKZ
        {
            get
            {
                if (ChkEKPBEKZ.IsChecked == true)
                {
                    return "N";
                }
                return " ";
            }
        }
        string EKPME3
        {
            get
            {
                if (ChkEKPME3.IsChecked == true)
                {
                    return "Y";
                }
                return "N";
            }
        }
        decimal wgPackage
        {
            get
            {
                if (txtPackgewg.Text.ToString().Trim() == "")
                {
                    txtPackgewg.Text = "0";
                }
                return System.Convert.ToDecimal(txtPackgewg.Text.ToString());
            }
            set
            {
                if (value.ToString().Trim() == "")
                {
                    value = 0;
                }
                txtPackgewg.Text = value.ToString();
            }
        }
        decimal EKNQTY
        {
            get
            {
                if (txtEKNQTy.Text.ToString().Trim() == "")
                {
                    txtEKNQTy.Text = "0";
                }
                return System.Convert.ToDecimal(txtEKNQTy.Text.ToString());
            }
            set
            {
                if (value.ToString().Trim() == "")
                {
                    value = 0;
                }
                txtEKNQTy.Text = value.ToString();
            }
        }
        decimal NWidth
        {
            get
            {
                if (txtNWidth.Text.ToString().Trim() == "")
                {
                    txtNWidth.Text = "0";
                }
                return System.Convert.ToDecimal(txtNWidth.Text.ToString());
            }
            set
            {
                if (value.ToString().Trim() == "")
                {
                    value = 0;
                }
                txtNWidth.Text = value.ToString();
            }
        }
        decimal Width
        {
            get
            {
                if (txtWidth.Text.ToString().Trim() == "0")
                {
                    txtWidth.Text = txtNWidth.Text;
                }
                return System.Convert.ToDecimal(txtWidth.Text.ToString());
            }
            set
            {
                if (value.ToString().Trim() == "")
                {
                    value = NWidth;
                }
                txtWidth.Text = value.ToString();
            }
        }
        decimal WidthRatio
        {
            get
            {
                if (txtWidthRatio.Text.ToString().Trim() == "")
                {
                    return 1;
                }
                if (txtWidth.Text.ToString().Trim() == "")
                {
                    return 1;
                }
                if (txtNWidth.Text.ToString().Trim() == "")
                {
                    return 1;
                }
                return System.Convert.ToDecimal(txtWidthRatio.Text);
            }
            set
            {
                txtWidthRatio.Text = value.ToString();
            }
        }
        string KRS
        {
            get
            {

                return Helper.Right("  " + txtEKKRS.Text.ToString().Trim(), 2);
            }
        }
        string LFD
        {
            get
            {

                return Helper.Right("000000 " + txtEKLFD.Text.ToString().Trim(), 6);
            }
        }
        CollectionViewSource vwABPOS_MAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPOS_MAT");
            }
        }
        DataRow dwABPOS_MAT
        {
            get
            {
                if (vwABPOS_MAT.View == null)
                    return null;
                if ((DataRowView)vwABPOS_MAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPOS_MAT.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwEKPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwEKPOS");
            }
        }

        CollectionViewSource vwYARNMatrix
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwYARNMatrix");
            }
        }
        CollectionViewSource vwFABMatrix
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwFABMatrix");
            }
        }
        CollectionViewSource vwMATMatrix
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwMATMatrix");
            }
        }

        CollectionViewSource vwABPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPOS");
            }
        }
        DataRow dwABPOS
        {
            get
            {
                if (vwABPOS.View == null)
                    return null;
                if ((DataRowView)vwABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPOS.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwFDECKMAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwFDECKMAT");
            }
        }
        DataRow dwFDECKMAT
        {
            get
            {
                if (vwFDECKMAT.View == null)
                    return null;
                if ((DataRowView)vwFDECKMAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwFDECKMAT.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwWDECKMAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwWDECKMAT");
            }
        }
        DataRow dwWDECKMAT
        {
            get
            {
                if (vwWDECKMAT.View == null)
                    return null;
                if ((DataRowView)vwWDECKMAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwWDECKMAT.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwWDECK
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwWDECK");
            }
        }
        DataRow dwWDECK
        {
            get
            {
                if (vwWDECK.View == null)
                    return null;
                if ((DataRowView)vwWDECK.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwWDECK.View.CurrentItem).Row;
            }
        }

        BindingListCollectionView cvWDECK
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(WDECKDataGrid.ItemsSource);
            }
        }
        BindingListCollectionView cvABAUFM
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgABAUFM.ItemsSource);
            }
        }
        DataRow dwEKPOS
        {
            get
            {
                if (vwEKPOS.View == null)
                    return null;
                if ((DataRowView)vwEKPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwEKPOS.View.CurrentItem).Row;
            }
        }

        CollectionViewSource vwABKOPF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABKOPF");
            }
        }
        DataRow dwABKOPF
        {
            get
            {
                if (vwABKOPF.View == null)
                    return null;
                if ((DataRowView)vwABKOPF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABKOPF.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwLIEFDAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwLIEFDAT");
            }
        }
        DataRow dwLIEFDAT
        {
            get
            {
                if (vwLIEFDAT.View == null)
                    return null;
                if ((DataRowView)vwLIEFDAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwLIEFDAT.View.CurrentItem).Row;
            }
        }
        string ART
        {
            get
            {
                return m_Data.Left(txtFSART.Text.ToString() + "                      ", 20);
            }
        }
        string mtype
        {
            get
            {
                return cbWTYE.Text;
            }
        }
        string user = "";
        #endregion
        public YCAFSPLAN()
        {
            InitializeComponent();
            this.Name = "投产规划";
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            dicParamater["blBuildCellMastrix"] = false;
            base.SetUp(dicParamater);
            InitializeComponent();
            this.dicParamater = dicParamater;
            OracleDB = (OracleConnection)dicParamater["OracleDB"];
            proxy = (IntexReptServBLClient)dicParamater["proxy"];
            tbUser = (DataTable)dicParamater["USERRIGHT"];
            m_Data = new YCAFSPLANData(OracleDB, proxy);
            user = (string)dicParamater["User"];
            txtFSART.Text = "B140400205          ";
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                SetEnv.Merge(m_Data.LoadAssData());
                vwEKPOS.View.CurrentChanged += vwEKPOS_CurrentChanged;
                vwWDECK.View.CurrentChanged += vwWDECK_CurrentChanged;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }

        void vwWDECK_CurrentChanged(object sender, EventArgs e)
        {
            if (dwWDECK == null)
                return;
            txtFSART.Text = dwWDECK["WDART"].ToString();
            SetData.Clear();
        }
        void vwEKPOS_CurrentChanged(object sender, EventArgs e)
        {

            if (dwEKPOS == null)
                return;
            btnFilterClear_Click(null, null);
            if (LastRow == dwEKPOS)
                return;
            LastRow = dwEKPOS;
            CheckFunction(cbWTYE.Text);
            if (dwEKPOS["EKPAUFKRS"].ToString()== "RP")
            {
                btnUpdateIntex.IsEnabled = false;
                btnApprove.IsEnabled = false;
                IsAutoBackCalulate = false;
                ChkEKPME3.IsEnabled = false;
                btnPushQty.IsEnabled = false;
                zoneMainFabric.Visibility = Visibility.Hidden;
            }
            btnFilter_Click(null, null);            
            try
            {

                DataSet SResult = new DataSet();
                using (new LongOperation(this, "数据更新中"))
                {
                    WidthRatio = 0;
                    SResult = m_Data.GetDECK(SetData, dwEKPOS);
                    SetData.ICC_ABKOPF.Clear();
                    if (SResult.Tables.Contains("ICC_ABKOPF"))
                    {
                        SetData.Merge(SResult.Tables["ICC_ABKOPF"]);
                    }
                    SetProd.Clear();
                    SetProd.Merge(SResult);
                    ResetData();
                    btnQtyCost_Click(null, null);
                    zoneQty.Visibility = Visibility.Hidden;
                    zoneQty.IsExpanded = false;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private bool PassCheck(DataSet src)
        {
            bool result = true;
            try
            {
                decimal qty = System.Convert.ToDecimal(txtEKNQTy.Text.ToString());
                var query = from DataRow row in SetProd.ICC_WDECKMAT.AsEnumerable()
                            where row["ART"].ToString().Trim() == dwEKPOS["EKPART"].ToString().Trim()
                            && row["VAR"].ToString().Trim() == dwEKPOS["EKPVAR"].ToString().Trim()
                            && row["FARBE"].ToString().Trim() == dwEKPOS["EKPFARBE"].ToString().Trim()
                            select row;
                foreach (DataRow row in query)
                {
                    decimal RLFD = System.Convert.ToDecimal(row["FGRLFD"].ToString());
                    if (row["UM"].ToString() == "KG")
                    {
                        //qty = qty / RLFD * 1000;
                        qty = System.Math.Round(qty / RLFD * 1000, 0);
                    }
                }
                decimal rqty = 0;
                var qxd = from XD in src.Tables["ICC_ABAUFM"].AsEnumerable()
                          where XD["ABAAUFKRS"].ToString() == dwEKPOS["EKPAUFKRS"].ToString()
                           && XD["ABAAUFLFD"].ToString().Trim() == dwEKPOS["EKPAUFLFD"].ToString().Trim()
                           && XD["ABAAUFPOS"].ToString() == dwEKPOS["EKPAUFPOS"].ToString()
                          group XD by new
                          {
                              ART = XD["ABAAUFKRS"].ToString(),
                              VAR = XD["ABAAUFLFD"].ToString(),
                              FARBE = XD["ABAAUFPOS"].ToString(),
                          }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  ABAQTYRESERVE = g.Sum(XD => Convert.ToDecimal(XD.Field<Decimal>("ABAQTYRESERVE"))),
                              };

                foreach (var XD in qxd)
                {
                    rqty = System.Math.Round(XD.ABAQTYRESERVE, 0);
                }
                if (System.Convert.ToDouble(rqty - qty) >= 0.01)
                {
                    result = false;
                    if (MessageBox.Show("面料供应数量" + qty + "<需求数量" + rqty, "请确认!", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return result;
        }
        void ResetData()
        {
            using (new LongOperation(this, "数据更新中"))
            {
                DataSet SResult = m_Data.ResetData(SetProd);
                SetProd.Clear();
                SetProd.Merge(SResult);
                if (!PassCheck(SResult))
                {
                    SetProd.Clear();
                    return;
                }
                string mart = dwEKPOS["EKPART"].ToString();
                string mvar = dwEKPOS["EKPVAR"].ToString();
                string mcolor = dwEKPOS["EKPFARBE"].ToString();
                string UM = dwEKPOS["EKPMEEH"].ToString().Trim();
                foreach (DataRow rap in SetProd.ICC_ABPOS_MAT.Rows)
                {
                    decimal mqty = 0;
                    decimal FGRLFD = 1;
                    var qxd = from DataRow XD in SetProd.WDECK.AsEnumerable()
                              where XD["WDAUFKRS"].ToString() == rap["KRS"].ToString()
                              && XD["WDAUFLFD"].ToString() == rap["LFD"].ToString()
                              && XD["WDART"].ToString().Trim() == mart.Trim()
                              && XD["WDVAR"].ToString().Trim() == mvar.Trim()
                              && XD["WDFARBE"].ToString().Trim() == mcolor.Trim()
                              select XD;
                    foreach (DataRow XD in qxd)
                    {
                        mqty += System.Convert.ToDecimal(XD["WDBEDARF"].ToString()) / 100;
                        rap["UM"] = UM;
                        rap["RATIO"] = XD["RATIO"];//比例     
                        FGRLFD = System.Convert.ToDecimal(XD["FGRLFD"].ToString());
                        rap["PQCDAT"] = FGRLFD;
                    }
                    rap["PCQTY"] = mqty;//面料用量                    
                    if (UM == "KG")
                    {
                        rap["PCQTY"] = System.Math.Round(System.Convert.ToDecimal((FGRLFD / 1000) * mqty), 2);
                    }
                    rap["PPQTY"] = rap["PCQTY"];//记录下来现在的值，用于将来放大倍数                            
                }
            }
        }
        private void btnQueryEKPOS_Click(object sender, EventArgs e)
        {
            try
            {//FSMANDANT	FSART	FSVAR
                string client = "00", wakz = "F", art = "", var = "", color = "", size = "       ";
                if (mtype.Trim() == "")
                { MessageBox.Show("必需选择类型"); return; }
                switch (mtype)
                {
                    case "成衣":
                        IsAutoBackCalulate = false;
                        wakz = " ";
                        art = ART;
                        break;
                    case "主面料":
                        wakz = "F";
                        IsAutoBackCalulate = true;
                        art = ART;
                        break;
                    case "面辅料":
                        IsAutoBackCalulate = false;
                        wakz = "F";
                        art = m_Data.Left(ART + "            ", 14);
                        break;
                    case "高级辅料":
                        IsAutoBackCalulate = false;
                        wakz = " ";
                        art = ART;
                        break;
                }
                DataSet SResult = new DataSet();
                using (new LongOperation(this, "数据更新中"))
                {
                    SResult = m_Data.GetEKPOS(client, wakz, art, var, color, size, EKPBEKZ, EKPME3);
                    SetData.Clear();
                    SetData.Merge(SResult);
                    if (vwEKPOS.View != null)
                    {
                        vwEKPOS.View.MoveCurrentToFirst();
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnQueryEKPOS2_Click(object sender, EventArgs e)
        {

            try
            {
                string client = "00", wakz = "F", art = "", var = "", color = "", size = "       ";
                if (mtype.Trim() == "")
                { 
                    MessageBox.Show("必需选择类型"); 
                    return;
                }
                switch (mtype)
                {
                    case "成衣":
                        IsAutoBackCalulate = false;
                        wakz = " ";           
                        break;
                    case "主面料":
                        wakz = "F";
                        IsAutoBackCalulate = true;                     
                        break;
                    case "面辅料":
                        IsAutoBackCalulate = false;
                        wakz = "F";                     
                        break;
                    case "高级辅料":
                        IsAutoBackCalulate = false;
                        wakz = " ";                      
                        break;
                }
                DataSet SResult = new DataSet();
                DataRow dwData = SetData.EKPOS.NewRow();
                dwData["EKPMANDANT"] = "00";
                dwData["EKPAUFKRS"] = KRS;
                dwData["EKPAUFLFD"] = LFD;
                dwData["EKPBEKZ"] = EKPBEKZ;

                SResult = m_Data.GetEKPOS(dwData, EKPME3);
                SetData.Clear();
                SetData.Merge(SResult);
                if (vwEKPOS.View != null)
                {
                    vwEKPOS.View.MoveCurrentToFirst();
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            DataSet setRpt = new DataSet();
            if (setRpt == null)
                return;
            m_DataX = new YCAFSPLANData(dicParamater);
            m_DataX.OracleDB = this.OracleDB;
            m_DataX.proxy = this.proxy;
            if (m_DataX.exAgent._app == null)
            {
                m_DataX.exAgent = new ExcelX.ExcelLib.ExcelAgent(dicParamater);
            }
            m_rpt = new YCAFSPLANReport(dicParamater);
            m_rpt.dsSource = SetProd;
            m_rpt.exAgent = m_DataX.exAgent;
            m_rpt.WriteExcelReport("EXCEL");
        }

        private void btnUpdateIntex_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (new LongOperation(this, "数据更新中"))
                {
                    ChangeStatus("98", "SP");
                    string text = m_Data.Save2Intex(SetProd);
                    txtEKP.Text = text + txtEKP.Text;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void ChangeStatus(string code, string status)
        {
            try
            {
                if (dwEKPOS == null)
                    return;
                string art = dwEKPOS["EKPART"].ToString();
                string var = dwEKPOS["EKPVAR"].ToString();
                string color = dwEKPOS["EKPFARBE"].ToString();
                var qwd = from DataRow row in SetProd.WDECK.AsEnumerable()
                          where row["WDART"].ToString().Trim() == art.Trim()
                          && row["WDVAR"].ToString().Trim() == var.Trim()
                          && row["WDFARBE"].ToString().Trim() == color.Trim()
                          select row;
                foreach (DataRow row in qwd)
                {
                    DataRow dwABPOS = m_Data.INTEXDB.ABPOS.NewRow();
                    string krs = row["WDAUFKRS"].ToString();
                    string lfd = row["WDAUFLFD"].ToString();
                    var qab = from AB in SetProd.ICC_ABPOS_MAT.AsEnumerable()
                              where AB["KRS"].ToString() == krs
                              && AB["LFD"].ToString() == lfd
                              && AB["ABPSPGRD"].ToString() == "89"
                              select AB;
                    if (qab.Count() > 0)
                    {
                        MessageBox.Show("该面料数量已经确认，辅料可能已经采购");
                        continue;
                    }
                    dwABPOS["ABPMANDANT"] = "00";
                    dwABPOS["ABPAUFKRS"] = row["WDAUFKRS"];
                    dwABPOS["ABPAUFLFD"] = row["WDAUFLFD"];
                    dwABPOS["ABPAUFPOS"] = row["WDAUFPOS"];
                    dwABPOS["ABPSPGRD"] = code;
                    dwABPOS["ABPGESSTA"] = status;
                    m_Data.INTEXDBC.UpdateABPOS(dwABPOS, 1);
                    string processed = txtEKP.Text;
                    string text = dwABPOS["ABPAUFKRS"].ToString().Trim() + "-" + dwABPOS["ABPAUFLFD"].ToString().Trim() + "已审核";
                    if (processed.Contains(text))
                        continue;
                    txtEKP.Text = text + Environment.NewLine + txtEKP.Text;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnApprove_Click(object sender, RoutedEventArgs e)
        {
            ChangeStatus("89", "SP");
        }
        private void AutoAllocation()
        {
            try
            {
                /*
                row["ABAAUFTYP"] = "N";
                row["ABAAUFKRS"] = "  ";
                row["ABAAUFLFD"] = "      ";
                row["ABAAUFPOS"] = "   ";
                row["ABAQTYALLOCATE"] = 0;
                row["ABAQTYRESERVE"] = 0;*/
                decimal ekqty = System.Convert.ToDecimal(txtEKNQTy.Text);

                decimal ratio = 1;
                decimal ABARESMG = 1;
                var qxd = from EKP in SetData.ICC_ABAUFM.AsEnumerable()
                          where EKP["ABAAUFTYP"].ToString() == "P"
                       && EKP["ABAAUFKRS"].ToString() == dwEKPOS["EKPAUFKRS"].ToString()
                       && EKP["ABAAUFLFD"].ToString() == dwEKPOS["EKPAUFLFD"].ToString()
                       && EKP["ABAAUFPOS"].ToString() == dwEKPOS["EKPAUFPOS"].ToString()
                          group EKP by new
                          {
                              TYP = EKP["ABAAUFTYP"].ToString(),
                          }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  ABARESMG = g.Sum(EKP => Convert.ToDecimal(EKP.Field<Decimal>("ABARESMG"))),
                              };
                foreach (var q in qxd)
                {
                    if (q.KEY.TYP.ToString() == "P")
                    {
                        ABARESMG = q.ABARESMG;
                    }
                }
                var query = from DataRow row in SetData.ICC_ABAUFM.AsEnumerable()
                            where row["ABAAUFTYP"].ToString() == "P"
                            && row["ABAAUFKRS"].ToString() == dwEKPOS["EKPAUFKRS"].ToString()
                            && row["ABAAUFLFD"].ToString() == dwEKPOS["EKPAUFLFD"].ToString()
                            && row["ABAAUFPOS"].ToString() == dwEKPOS["EKPAUFPOS"].ToString()
                            select row;
                foreach (DataRow row in query)
                {
                    decimal qty = System.Convert.ToDecimal(row["ABARESMG"].ToString());
                    ratio = qty / ABARESMG;
                    row["ABAQTYRESERVE"] = System.Math.Round(ratio * ekqty, 2);
                    m_Data.INTEXDBC.UpdateICC_ABAUFM(row, 1);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnPushQty_Click(object sender, RoutedEventArgs e)
        {
            if (!IsAutoBackCalulate)
            {
                AutoAllocation();
                return;
            }
            if (dwEKPOS == null)
                return;
            if (txtEKQTy.Text.Trim() == "")
                txtEKQTy.Text = "0";
            string art = dwEKPOS["EKPART"].ToString();
            string var = dwEKPOS["EKPVAR"].ToString();
            string color = dwEKPOS["EKPFARBE"].ToString();
            string UM = dwEKPOS["EKPMEEH"].ToString();
            double lastqty = 0, newqty = 0;
            string szQty = "0";
            decimal ekqty = System.Convert.ToDecimal(txtEKNQTy.Text.ToString());
            //获取
            int count = SetProd.ICC_ABPOS_MAT.Rows.Count;
            /*  string grm = SetProd.ICC_ABPOS_MAT.Rows[0]["PQCDAT"].ToString();
            if (grm.Trim() == "")
                grm = "0";
            double RLFD = System.Convert.ToDouble(grm);
          if (UM == "KG")
            {
                ekqty = ekqty / RLFD * 1000;
            }*/
            decimal qty = 0;
            int ix = 0;
            foreach (DataRow row in SetProd.ICC_ABPOS_MAT.Rows)
            {
                ix++;
                decimal mqty = System.Convert.ToDecimal(row["PCQTY"].ToString());
                decimal moqty = System.Convert.ToDecimal(row["PPQTY"].ToString());
                decimal ratio = System.Convert.ToDecimal(row["RATIO"].ToString());//比例                   
                if (ix == count)
                {
                    mqty = ekqty - qty;
                    row["PCQTY"] = mqty;
                }
                qty += mqty;
                decimal rate = mqty / moqty;
                decimal sqty = System.Math.Floor(System.Convert.ToDecimal(row["S"].ToString()) * rate);
                row["S"] = System.Math.Floor(sqty);
                sqty = System.Math.Floor(System.Convert.ToDecimal(row["M"].ToString()) * rate);
                row["M"] = System.Math.Floor(sqty);
                sqty = System.Math.Floor(System.Convert.ToDecimal(row["L"].ToString()) * rate);
                row["L"] = System.Math.Floor(sqty);
                sqty = System.Math.Floor(System.Convert.ToDecimal(row["XL"].ToString()) * rate);
                row["XL"] = System.Math.Floor(sqty);
                var query = from DataRow rx in SetProd.ABPOS.AsEnumerable()
                            where rx["ABPART"].ToString().Trim() == row["ABPART"].ToString().Trim()
                            && rx["ABPFARBE"].ToString().Trim() == row["ABPFARBE"].ToString().Trim()
                            select rx;
                foreach (DataRow rx in query)
                {
                    switch (rx["ABPGROE"].ToString().Trim())
                    {
                        case "S":
                            rx["ABPSOLLMENGE7"] = System.Convert.ToDecimal(row["S"].ToString()) * 100;
                            break;
                        case "M":
                            rx["ABPSOLLMENGE7"] = System.Convert.ToDecimal(row["M"].ToString()) * 100;
                            break;
                        case "L":
                            rx["ABPSOLLMENGE7"] = System.Convert.ToDecimal(row["L"].ToString()) * 100;
                            break;
                        case "XL":
                            rx["ABPSOLLMENGE7"] = System.Convert.ToDecimal(row["XL"].ToString()) * 100;
                            break;
                    }
                }
            }
            SetProd.AcceptChanges();
            ResetData();
        }

        private void btnRefreshEKP_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DataRow dwData = dwEKPOS.Table.Clone().NewRow();
                dwData.ItemArray = dwEKPOS.ItemArray;
                double qty = System.Convert.ToDouble(dwData["EKPME1"].ToString()) * 100;
                dwData["EKPME1"] = qty;
                double price = System.Convert.ToDouble(dwData["EKPPRME"].ToString()) * 0.001;
                if (dwData["EKPPRME"].ToString().Trim() == "")
                {
                    dwData["EKPPRME"] = "0";
                }
                dwData["EKPWE1"] = System.Math.Round(qty * price, 0);
                dwData["EKPBEKZ"] = "N";
                m_Data.INTEXDBC.UpdateEKPOS(dwData, 2);
                m_Data.INTEXDBC.UpdateEKPOS(dwData, 21);
                m_Data.INTEXDBC.UpdateEKKOPF(dwData, 21);
                dwData = SetData.EKKOPF.NewRow();
                dwData["EKKMANDANT"] = "00";
                dwData["EKKAUFKRS"] = dwEKPOS["EKPAUFKRS"];
                dwData["EKKAUFLFD"] = dwEKPOS["EKPAUFLFD"];
                m_Data.INTEXDBC.UpdateEKKOPF(dwData, 2);
                string text = dwData["EKKAUFKRS"].ToString() + dwData["EKKAUFLFD"].ToString() + "已保存";
                txtEKP.Text = text + Environment.NewLine + txtEKP.Text;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }


        }
        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            string filter = "ABAAUFTYP ='P' AND ABAAUFKRS='" + dwEKPOS["EKPAUFKRS"].ToString() + "' AND ABAAUFLFD='"
                + dwEKPOS["EKPAUFLFD"].ToString() + "' AND ABAAUFPOS='" + dwEKPOS["EKPAUFPOS"].ToString() + "'";
            cvABAUFM.CustomFilter = filter;
        }

        private void btnFilterClear_Click(object sender, RoutedEventArgs e)
        {
            cvABAUFM.CustomFilter = null;
        }
        private void cbSECTION_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            txtSection.Text += cb.SelectedValue + ";";
        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            if (dwEKPOS == null)
            {
                MessageBox.Show("请选择采购单!");
                return;
            }
            if (dwABPOS_MAT == null)
            {
                MessageBox.Show("请选择需要移除的款!");
                return;
            }
            if (dwABPOS_MAT["ABPSPGRD"].ToString().Trim() == "89"
                || dwABPOS_MAT["ABPSPGRD"].ToString().Trim() == ""
                )
            {
                MessageBox.Show("已经确认，禁止删除!");
                return;
            }
            string KRS = dwABPOS_MAT["KRS"].ToString();
            string LFD = dwABPOS_MAT["LFD"].ToString();
            string ABPART = dwABPOS_MAT["ABPART"].ToString();
            string ABPFARBE = dwABPOS_MAT["ABPFARBE"].ToString();
            string abaidlist = "";
            var query = from DataRow row in SetData.ICC_ABAUFM.AsEnumerable()
                        where row["ABAAUFTYP"].ToString() == "P"
                        && row["ABAAUFKRS"].ToString() == dwEKPOS["EKPAUFKRS"].ToString()
                        && row["ABAAUFLFD"].ToString() == dwEKPOS["EKPAUFLFD"].ToString()
                        && row["ABAAUFPOS"].ToString() == dwEKPOS["EKPAUFPOS"].ToString()
                        && row["ABAVKAUFKRS"].ToString() == KRS
                        && row["ABAVKAUFLFD"].ToString() == LFD
                        && row["ABPART"].ToString() == ABPART
                        && row["ABPFARBE"].ToString() == ABPFARBE
                        select row;
            if (query.Count() == 1)
            {
                MessageBox.Show("最后一行了，禁止删除!");
                return;
            }
            foreach (DataRow row in query)
            {
                row["ABAAUFTYP"] = "N";
                row["ABAAUFKRS"] = "  ";
                row["ABAAUFLFD"] = "      ";
                row["ABAAUFPOS"] = "   ";
                row["ABAQTYALLOCATE"] = 0;
                row["ABAQTYRESERVE"] = 0;
                abaidlist += "'" + row["ABAID"].ToString() + "',";
                m_Data.INTEXDBC.UpdateICC_ABAUFM(row, 1);
            }
            DataRow[] rows = SetProd.ICC_ABPOS_MAT.Select("KRS = '" + KRS + "' AND LFD='" + LFD + "' AND ABPART='" + ABPART + "' AND ABPFARBE='" + ABPFARBE + "'");
            foreach (DataRow rw in rows)
            {
                rw.Delete();
            }
            rows = SetData.ICC_ABAUFM.Select("ABAID IN (" + abaidlist + ")");
            foreach (DataRow rw in rows)
            {
                rw.Delete();
            }
            SetData.AcceptChanges();
        }
        private void btnCheck_Click(object sender, RoutedEventArgs e)
        {
            using (new LongOperation(this, "读取符合条件的记录"))
            {
                SetEnv.WDECK.Clear();
                SetEnv.FDECK.Clear();
                DataSet SResult = m_Data.LoadGXDECKData(mtype, txtSection.Text, EKPBEKZ);
                SetEnv.Merge(SResult);
            }
        }
        void CheckFunction(string mtyp)
        {
            zoneMainFabric.Visibility = Visibility.Hidden;
            btnPushQty.IsEnabled = false;
            switch (mtyp)
            {
                case "成衣":
                    IsAutoBackCalulate = false;
                    btnUpdateIntex.IsEnabled = false;
                    btnApprove.IsEnabled = false;
                    ChkEKPME3.IsEnabled = false;
                    break;
                case "主面料":
                    zoneMainFabric.Visibility = Visibility.Visible;
                    btnUpdateIntex.IsEnabled = true;
                    btnPushQty.IsEnabled = true;
                    btnApprove.IsEnabled = true;
                    IsAutoBackCalulate = true;
                    ChkEKPME3.IsEnabled = false;
                    break;
                case "面辅料":
                    btnUpdateIntex.IsEnabled = false;
                    btnApprove.IsEnabled = false;
                    IsAutoBackCalulate = false;
                    ChkEKPME3.IsEnabled = false;
                    break;
                case "高级辅料":
                    btnUpdateIntex.IsEnabled = false;
                    btnApprove.IsEnabled = false;
                    IsAutoBackCalulate = false;
                    ChkEKPME3.IsEnabled = true;
                    ChkEKPME3.IsChecked = true;
                    break;
            }
        }
        private void cbWTYE_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0)
                return;
            SetEnv.WDECK.Clear();
            string mtyp = ((ComboBoxItem)e.AddedItems[0]).Content.ToString();
            CheckFunction(mtyp);
        }
        private void btnQtyCost_Click(object sender, RoutedEventArgs e)
        {
            if (dwEKPOS == null)
                return;
            zoneQty.Visibility = Visibility.Visible;
            zoneQty.IsExpanded = true;
            txtEKNQTy.Text= txtEKQTy.Text;
            if (dwEKPOS["EKPEFARBE"].ToString().Trim() == "")
                return;
            if (WidthRatio == 0)
                WidthRatio = 1;
            EKNQTY = System.Convert.ToDecimal(dwEKPOS["EKPEFARBE"].ToString());

            if (dwEKPOS["EKPEART"].ToString().Trim() == "")
                return;
            string[] cost = dwEKPOS["EKPEART"].ToString().Split(new Char[] { ';' });
            wgPackage = System.Convert.ToDecimal(cost[0]);
            WidthRatio = System.Convert.ToDecimal(cost[1]);
            //wgPackage
            //EKPEART
            //EKPEFARBE
        }

        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            if (dwEKPOS == null)
                return;
            zoneQty.Visibility = Visibility.Hidden;
            zoneQty.IsExpanded = false;
            decimal EKPME1 = System.Convert.ToDecimal(dwEKPOS["EKPME1"].ToString());
            if (WidthRatio == 0)
            {
                WidthRatio = System.Math.Round(NWidth /Width, 3);
            }
            EKNQTY = (EKPME1 - wgPackage) * (WidthRatio);
            dwEKPOS["EKPEART"] = wgPackage + ";" + WidthRatio + ";";
            dwEKPOS["EKPEFARBE"] = EKNQTY;
            //wgPackage
            //EKPEART
            //EKPEFARBE
        }
    }
}
